<?php

namespace app\common\baota;
class Bt
{
    private $BT_KEY = "";    //接口密钥
    private $BT_PANEL = "";            //面板地址

    /**
     * 初始化
     * @param [type] $bt_panel 宝塔接口地址
     * @param [type] $bt_key   宝塔Api密钥
     */
    public function __construct($bt_panel = null, $bt_key = null)
    {
        if ($bt_panel) $this->BT_PANEL = $bt_panel;
        if ($bt_key) $this->BT_KEY = $bt_key;
    }

    /**
     * 获取系统基础统计
     */
    public function GetSystemTotal()
    {
        $url = $this->BT_PANEL . "/system?action=GetSystemTotal";
        $url = $this->BT_PANEL . "/system?action=GetNetWork";
        $p_data = $this->GetKeyData();

        $result = $this->HttpPostCookie($url, $p_data);
//        var_dump($result);
//        print_r($result);
        $data = json_decode($result, true);
//        print_r($data);
//        var_dump($data);
        return $data;
    }

    /**
     * 构造带有签名的关联数组
     */
    public function GetKeyData()
    {
        $now_time = time();
        $p_data = array(
            'request_token' => md5($now_time . '' . md5($this->BT_KEY)),
            'request_time' => $now_time
        );
        return $p_data;
    }

    /**
     * 发起POST请求
     * @param String $url 目标网填，带http://
     * @param Array|String $data 欲提交的数据
     * @return string
     */
    private function HttpPostCookie($url, $data, $timeout = 60)
    {
        //定义cookie保存位置
        $dir = './../runtime/baota/';
        $this->mkdirs($dir);
        $cookie_file = $dir . base64_encode($this->BT_PANEL) . '.cookie';
        if (!file_exists($cookie_file)) {
            $fp = fopen($cookie_file, 'w+');
            fclose($fp);
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_PROXY, "qqyun.itbbn.top"); //代理服务器地址
        curl_setopt($ch, CURLOPT_PROXYPORT, "38088"); //代理服务器端口
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }


    private function mkdirs($dir, $mode = 0777)
    {
        if (is_dir($dir) || @mkdir($dir, $mode)) return TRUE;
        if (!mkdirs(dirname($dir), $mode)) return FALSE;
        return @mkdir($dir, $mode);
    }

}
